<template>
  <div class="jsbos-common-layout">
    <div class="jsbos-common-layout-center">
      <el-row class="jsbos-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="4">
            <el-form-item label="关键词">
              <el-input
                v-model="query.keyWord"
                placeholder="请输入名称"
                clearable
                @keyup.enter.native="search"
              >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="query.orderStartDate"
                type="daterange"
                value-format="timestamp"
                format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @keyup.enter.native="search"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="开放类型 ">
              <el-select
                v-model="query.orderType"
                placeholder="请选择"
                clearable
                @keyup.enter.native="search"
              >
                <el-option
                  v-for="(item, index) in orderTypeOptions"
                  :key="index"
                  :label="item.fullName"
                  :value="item.enCode"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="状态">
              <el-select
                v-model="query.enabledMark"
                placeholder="请选择"
                clearable
                @keyup.enter.native="search"
              >
                <el-option
                  v-for="(item, index) in enabledMarkOptions"
                  :key="index"
                  :label="item.fullName"
                  :value="item.enCode"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click.native.prevent="search"
                >查询</el-button
              >
              <el-button icon="el-icon-refresh-right" @click="reset()"
                >重置</el-button
              >
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="jsbos-common-layout-main jsbos-flex-main">
        <div class="jsbos-common-head">
          <div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addOrUpdateHandle()"
              >新增
            </el-button>
            <!-- <el-button type="text" icon="el-icon-download" @click="exportData()"
              >导出
            </el-button> -->
          </div>
          <div class="jsbos-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link
                icon="icon-ym icon-ym-Refresh JSBOS-common-head-icon"
                :underline="false"
                @click="reset()"
              />
            </el-tooltip>
            <ScreenFull isContainer />
          </div>
        </div>
        <jsbos-table
          v-loading="listLoading"
          :data="list"
          @sort-change="sortChange"
        >
          <!-- <el-table-column
            prop="orderCode"
            label="任务编码"
            width="80"
            align="left"
          /> -->
          <el-table-column
            prop="orderName"
            label="任务标题"
            width="200"
            align="left"
          >
            <template slot-scope="scope">
              <el-link
                type="primary"
                :underline="false"
                @click="goDetail(scope.row.id)"
              >
                {{ scope.row.orderName }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            prop="questionnaireIdName"
            label="任务模板"
            width="150"
            align="left"
          />
          <el-table-column
            prop="orderType"
            label="开放类型"
            width="0"
            align="left"
          />
          <!-- <el-table-column prop="orderRange" label="内部范围" width="0" align="left" :show-overflow-tooltip="true" /> -->
          <el-table-column
            prop="orderStartDate"
            label="时间范围"
            width="170"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.orderStartDate + "至" + scope.row.orderEndDate }}
            </template>
          </el-table-column>
          <el-table-column
            prop="finishPersonNumber"
            label="答题情况"
            width="0"
            align="left"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="状态"
            width="100"
            prop="enabledMark"
            algin="left"
          >
            <!-- <template slot-scope="scope">
              {{ scope.row.enabledMark | dynamicText(enabledMarkOptions) }}
            </template> -->
            <template slot-scope="scope">
              <span :class="showClass(scope.row.enabledMark)" />&nbsp;
              <span
                :class="showClass(scope.row.enabledMark)"
                style="background: none; display: contents"
                >{{ getChangeEnabledMark(scope.row.enabledMark) }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="addOrUpdateHandle(scope.row.id)"
                >编辑
              </el-button>
              <el-button
                type="text"
                class="jsbos-table-delBtn"
                @click="handleDel(scope.row.id)"
                >删除
              </el-button>
              <el-button type="text" @click="viewResults(scope.row)"
                >答题情况
              </el-button>
              <el-button type="text" @click="createQrcode(scope.row)"
                >生成二维码
              </el-button>
            </template>
          </el-table-column>
        </jsbos-table>
        <pagination
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="initData"
        />
      </div>
    </div>
    <JSBOS-Form v-if="formVisible" ref="JSBOSForm" @refresh="refresh" />
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <Detail
      v-if="detailVisible"
      ref="Detail"
      @refresh="detailVisible = false"
    />
    <ResultDetail
      v-if="resultVisible"
      ref="resultDetail"
      @refresh="resultVisible = false"
    />
    <el-dialog
      :title="orderName"
      :visible.sync="qrcodeVisible"
      :close-on-click-modal="false"
      class="jsbos-dialog jsbos-dialog_center"
      lock-scroll
      width="450px"
    >
      <div class="qr_create">
        <div
          :id="'qrCode'"
          :ref="'qrCode'"
          :data-code="qrCode"
          style="
            width: 300px;
            height: 300px;
            border: 1px solid #eee;
            margin-bottom: 24px;
            margin-left: 24px;
          "
        ></div>
        <!-- 作为下载二维码使用 -->
        <a ref="downLoadImgUrl" style="display: none"></a>
      </div>
      <!-- <div class="qr_create_httpUrl">链接地址：{{ httpMUrl }}</div> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="qrcodeVisible = false">取 消</el-button>
        <el-button type="primary" @click="downQrcodeImg">下载二维码</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import { getDictionaryDataSelector } from "@/api/systemData/dictionary";
import JSBOSForm from "./Form";
import ExportBox from "./ExportBox";
import Detail from "./Detail";
import "../styles/index.scss";
import ResultDetail from "./components/Detail.vue";
import QRCode from "qrcodejs2";
import { getSystemAddress } from "@/api/user";
export default {
  components: { JSBOSForm, ExportBox, Detail, ResultDetail },
  data() {
    return {
      qrcodeVisible: false,
      qrCode: "",
      qrcodeImgUrl: "",
      httpMUrl: "",
      resultVisible: false,
      detailVisible: false,
      orderTypeOptions: [],
      sysAddress: "",
      orderName: "",
      query: {
        orderType: "",
        questionnaireId: undefined,
        keyWord: undefined,
        orderStartDate: undefined,
        orderEndDate: undefined,
        enabledMark: undefined,
      },
      treeProps: {
        children: "children",
        label: "fullName",
        value: "id",
      },
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatorTime",
      },
      formVisible: false,
      exportBoxVisible: false,
      columnList: [
        { prop: "questionnaireId", label: "任务模板" },
        { prop: "orderName", label: "任务标题" },
        { prop: "orderCode", label: "任务编码" },
        { prop: "orderRange", label: "内部包含范围" },
        { prop: "orderStartDate", label: "开始时间" },
        { prop: "orderEndDate", label: "结束时间" },
        { prop: "enabledMark", label: "状态" },
        { prop: "description", label: "任务描述" },
        { prop: "creatorUserId", label: "创建用户" },
        { prop: "creatorTime", label: "创建时间" },
      ],
      enabledMarkOptions: [],
    };
  },
  computed: {
    menuId() {
      return this.$route.meta.modelId || "";
    },
  },
  created() {
    this.initData();
    this.getorderTypeOptions();
    this.getenabledMarkOptions();
    this.getSystemAddress();
  },
  methods: {
    getSystemAddress() {
      getSystemAddress("app").then((res) => {
        var redirect_uri = encodeURIComponent(res.msg);
        this.sysAddress = res.msg;
      });
    },
    //不同状态显示不同的颜色
    showClass(item) {
      const describeForActiveNameMap = {
        0: () => "draft",
        10: () => "accepted",
        20: () => "emergent",
      };
      return describeForActiveNameMap[item]
        ? describeForActiveNameMap[item]()
        : "end";
    },
    // 状态 匹配 数据字典数据
    getChangeEnabledMark(e) {
      for (var i = 0; i < this.enabledMarkOptions.length; i++) {
        if (this.enabledMarkOptions[i].enCode == e) {
          return this.enabledMarkOptions[i].fullName;
        }
      }
    },

    //
    viewResults(row) {
      this.resultVisible = true;
      this.$nextTick(() => {
        this.$refs.resultDetail.init(row.id);
      });
    },
    //单元格根据内容实现的就是基本的逻辑处理了。
    // addClass({ row, column, rowIndex, columnIndex }) {
    //   if (column.label == "状态") {
    //     if (row.enabledMark == "0") {
    //       //row.enabledMark 对应列上的 prop="enabledMark"
    //       return "color:red;";
    //     } else if (row.enabledMark == "1") {
    //       return "color:green;";
    //     }
    //   }
    // },
    getenabledMarkOptions() {
      getDictionaryDataSelector("471639537894912325").then((res) => {
        this.enabledMarkOptions = res.data.list;
      });
    },
    getorderTypeOptions() {
      getDictionaryDataSelector("436127844121187333").then((res) => {
        this.orderTypeOptions = res.data.list;
      });
    },
    goDetail(id) {
      this.detailVisible = true;
      this.$nextTick(() => {
        this.$refs.Detail.init(id);
      });
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == "ascending" ? "asc" : "desc";
      this.listQuery.sidx = !order ? "" : prop;
      this.initData();
    },
    initData() {
      this.listLoading = true;
      let _query = {
        ...this.listQuery,
        ...this.query,
        menuId: this.menuId,
      };
      request({
        url: `/api/questionnaire/OqQuestionnaireOrder/getList`,
        method: "post",
        data: _query,
      }).then((res) => {
        var _list = [];
        for (let i = 0; i < res.data.list.length; i++) {
          let _data = res.data.list[i];
          _list.push(_data);
        }
        this.list = _list;
        this.total = res.data.pagination.total;

        this.listLoading = false;
      });
    },
    handleDel(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        type: "warning",
      })
        .then(() => {
          request({
            url: `/api/questionnaire/OqQuestionnaireOrder/${id}`,
            method: "DELETE",
          }).then((res) => {
            if (res.msg == "duplication") {
              this.$message.warning("当前任务有数据关联，请勿删除！");
              return;
            }
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.initData();
              },
            });
          });
        })
        .catch(() => {});
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true;
      this.$nextTick(() => {
        this.$refs.JSBOSForm.init(id, isDetail);
      });
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatorTime",
      };
      this.initData();
    },
    refresh(isrRefresh) {
      this.formVisible = false;
      if (isrRefresh) this.reset();
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined;
      }
      this.search();
    },
    createQrcode(row) {
      this.qrcodeVisible = true;
      if (!row) {
        return;
      }
      this.orderName = row.orderName + "二维码";
      const baseUrl = this.sysAddress.substring(
        0,
        this.sysAddress.indexOf("#")
      );
      let v =
        baseUrl +
        "/#/pages/os-questionnaire/questionnaire-write/writing?" +
        "id=" +
        row.id +
        "questionnaireOrderRangeId" +
        row;
      this.$nextTick(() => {
        const qrCodeRef = this.$refs["qrCode"];
        if (qrCodeRef) {
          qrCodeRef.innerHTML = ""; // 清空二维码容器
          new QRCode(qrCodeRef, {
            width: 300,
            height: 300,
            text: v,
            correctLevel: QRCode.CorrectLevel.M,
          });
          let qrcodeCanvas =
            this.$refs.qrCode.getElementsByTagName("canvas")[0];
          this.qrcodeImgUrl = qrcodeCanvas.toDataURL("image/png"); // 作为下载图片资源
        } else {
          console.error("QRCode ref is not defined");
        }
      });
    },
    // 下载二维码
    downQrcodeImg() {
      let downloadLink = this.$refs.downLoadImgUrl;
      downloadLink.setAttribute("href", this.qrcodeImgUrl);
      downloadLink.setAttribute(
        "download",
        `${this.qrDialogName}_${new Date().getTime()}.png`
      );
      downloadLink.click();
      URL.revokeObjectURL(downloadLink.href);
      this.qrcodeVisible = false;
    },
  },
};
</script>
<style>
.qr_create {
  width: 100%;
  display: flex;
  justify-content: center;
}

.qr_create_httpUrl {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}
</style>
